#include "infodialog.h"
#include "ui_infodialog.h"
#include "logic.h"
#include <QFileDialog>

InfoDialog::InfoDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::InfoDialog)
{
    ui->setupUi(this);
}

InfoDialog::~InfoDialog()
{
    delete ui;
}

void InfoDialog::setType(int type){
    this->type = type;
    ui->titleLabel->setStyleSheet("color:black;");
    if(type == InfoDlgType::ADD_ITEM){
        setTitle("新增配置");
        return;
    }

    if(type == InfoDlgType::MODIFY){
        setTitle("编辑配置");
    }else if(type == InfoDlgType::DELETE){
        ui->titleLabel->setStyleSheet("color:red;");
        setTitle("删除配置");
    }


    auto list = Logic::getInstance()->getItems();
    auto item = list[Logic::getInstance()->getCurIndex()].toObject();

    setContent(item);
}

void InfoDialog::setTitle(QString title){
    ui->titleLabel->setText(title);
}

void  InfoDialog::setContent(QJsonObject &item){
    ui->nameEdit->setText(item.value("name").toString());
    ui->dirEdit->setText(item.value("dir").toString());
    ui->excludeEdit->setText(item.value("filter").toString());
    ui->includeEdit->setText(item.value("url").toString());
    ui->commentEdit->setText(item.value("comment").toString());
}

void InfoDialog::on_buttonBox_accepted()
{
    if(type == InfoDlgType::ADD_ITEM || type == InfoDlgType::MODIFY){
        auto name = ui->nameEdit->text();
        if(name == "" || ui->dirEdit->text() == ""){
            ui->hint->setText("名称和路径不能为空");
            return;
        }

        QJsonObject item;
        item.insert("name",name);

        item.insert("dir",ui->dirEdit->text());
        item.insert("filter",ui->excludeEdit->text());
        item.insert("url",ui->includeEdit->text());
        item.insert("comment",ui->commentEdit->text());

        if(type == InfoDlgType::MODIFY){
            Logic::getInstance()->updateItem(item);
        }else{
            if(Logic::getInstance()->isHave(name)){
                ui->hint->setText("该名称已经存在");
                return;
            }
            Logic::getInstance()->append(item);
        }
    }else if(type == InfoDlgType::DELETE){
        qDebug()<<"remove";
        Logic::getInstance()->remove();
    }

    emit ev(type); // 触发发送数据的信号
    close();
}

void InfoDialog::on_buttonBox_rejected()
{
    close();
}


void InfoDialog::on_pickDir_clicked()
{
    // 打开文件资源管理器并选择文件夹
    QString dirPath = QFileDialog::getExistingDirectory(nullptr,"选择文件夹" , ui->dirEdit->text());
    ui->dirEdit->setText(dirPath);
}

